<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\Agent;
use App\Model\Order;
use App\Model\OrderDetail;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware(['admin']);
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $model = Order::where('id', '>', 0);
        !empty($params['agent_id']) && $model->where('agent_id', $params['agent_id']);
        !empty($params['order_num']) && $model->where('order_num', $params['order_num']);
        !empty($params['mobile']) && $model->whereRaw("uid in (select id from users where username = '{$params['mobile']}')");
        isset($params['pay_status']) && $params['pay_status'] !== '' && $model->where('pay_status', $params['pay_status']);
        isset($params['status']) && $params['status'] !== '' && $model->where('status', $params['status']);
        !empty($params['start']) && $model->where('created_at', '>', $params['start']);
        !empty($params['end']) && $model->where('created_at', '<=', $params['end'] . ' 23:59:59');
        $list = $model->orderBy('id', 'desc')->paginate(15);

        return view('admin.order.index', [
            'list' => $list,
            'params' => $params,
            'statusLabels' => Order::$statusLabels,
            'agents' => Agent::pluck('name', 'id')->toArray(),
        ]);
    }

    public function detail(Request $request)
    {
        $order = Order::with('user')->find($request->input('order_id'));
        return view('admin.order.detail', [
            'order' => $order,
            'statusLabels' => Order::$statusLabels,
            'details' => OrderDetail::where('order_id', $order['id'])->get(),
        ]);
    }

    public function finance(Request $request)
    {
        $params = $request->all();
        $start = empty($params['start']) ? date('Y-m-d') : $params['start'];
        $end = empty($params['end']) ? date('Y-m-d') : $params['end'];

        $list = Agent::where('status', 1)->where(function ($query) use ($params) {
            !empty($params['agent_id']) && $query->where('id', $params['agent_id']);
        })->paginate(10);
        foreach ($list as $k => $v) {
            $row = Order::getFinanceInfo($v['id'], $start, $end);
            $list[$k]['finance'] = $row;
        }

        return view('admin.order.finance', [
            'list' => $list,
            'start' => $start,
            'end' => $end,
            'params' => $params,
            'agents' => Agent::where('status', 1)->pluck('name', 'id')->toArray(),
        ]);
    }
}